﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using MyApp.WebApi.Common;
using StackExchange.Profiling;
using Blog.Core.Common;
using System.IO;

namespace MyApp.WebApi.Extensions
{
    public static class SqlSugarSetup
    {
        /// <summary>
        /// SqlSugar注入到容器
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSqlSugarSetup(this IServiceCollection services)
        {

            List<ConnectionConfig> List = AppSettings.AppList<ConnectionConfig>(new string[] { "ConnectionConfigs" });
            #region 可为空类型，对照到数据库is null
            ConfigureExternalServices ConfigureExternalServices = new ConfigureExternalServices
            {
                //注意:  这儿AOP设置不能少
                EntityService = (c, p) =>
                {
                    /***低版本C#写法***/
                    // int?  decimal?这种 isnullable=true 不支持string(下面.NET 7支持)
                    if (p.IsPrimarykey == false && c.PropertyType.IsGenericType &&
                    c.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        p.IsNullable = true;
                    }

                }
            };
            foreach (var item in List)
            {
                if (item.DbType == DbType.Sqlite)//sqllite
                {
                    item.ConnectionString = $"DataSource=" + Path.Combine(Environment.CurrentDirectory, item.ConnectionString);
                    //NLogHelper.GetLog().Info("连接字符串"+ item.ConnectionString);
                }
                NLogHelper.GetLog().Info("连接字符串" + item.ConnectionString);
                item.ConfigureExternalServices = ConfigureExternalServices;
                //item.SlaveConnectionConfigs=
            }
            #endregion
            SqlSugarScope Db = new SqlSugarScope(List,
             db =>
             {
                 db.Aop.OnLogExecuting = (sql, p) =>
                 {
                     Parallel.For(0, 1, e =>
                     {
                         MiniProfiler.Current.CustomTiming("SQL：", GetParas(p) + "【SQL语句】：" + sql);
                     });
                 };
             });
            services.AddSingleton<SqlSugarScope>(Db);
            return services;
        }

        private static string GetParas(SugarParameter[] pars)
        {
            string key = "【SQL参数】：";
            foreach (var param in pars)
            {
                key += $"{param.ParameterName}:{param.Value}\n";
            }

            return key;
        }
    }
}
